package com.packet.cheng.interceptor;

import com.packet.cheng.annotation.RedisLock;
import com.packet.cheng.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 @author zaicheng
 @version 1.0
 @date 2022-04-19
 @email zzc15847256473@163.com
 */

@Component
@Aspect
@Slf4j
public class RedisLockInterceptor {

    @Resource
    private Redisson redisson;
    
//    @Pointcut("execution(* com.packet.cheng.service.*.*(..))")
//    public  void  point(){
//
//    }
//
//    // 环绕通知，用于在执行业务方法前后加入对应增强逻辑
//    @Around(value = "point()")
//    public Object around(ProceedingJoinPoint joinPoint) throws  Throwable{
//
//        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//
//        Method method = methodSignature.getMethod();
//
//        RedisLock redisLock = method.getAnnotation(RedisLock.class);
//
//        String prefix = StringUtil.isBlank(redisLock.prefixValue()) ? "" : redisLock.prefixValue();
//
//        String key = "";
//
//        return null; // executionWithLockSevice(prefix + ":" + key, redisLock.waitTime(), redisLock.unit(), joinPoint::proceed);
//    }
//
//    // 执行锁逻辑的公用方法
//    public  <T> T  executionWithLockSevice(String key,int waitTime ,TimeUnit unit, Supplier<T> supplier) throws Throwable {
//
//        RLock rLock = redisson.getLock(key);
//
//        boolean tryLock = rLock.tryLock(waitTime,unit);
//
//        if (!tryLock){
//            throw  new RuntimeException("获取分布式锁失败，请稍后重试");
//        }
//        try{
//
//           return  supplier.get();
//
//        }catch (Exception e){
//                throw  e;
//        }finally {
//            if (rLock.isLocked() && rLock.isHeldByCurrentThread()){
//                rLock.unlock();
//            }
//        }
////        return  null;
//    }


}
